import axios from 'axios';
//引入mock
import '../mock/index'
// 从环境变量中获取baseUrl和base
const {REACT_APP_BASE_URL,REACT_APP_BASE} = process.env;



// 创建axios实例
const instance = axios.create({
    baseURL: REACT_APP_BASE_URL + REACT_APP_BASE,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
});

// 请求拦截器
instance.interceptors.request.use(config => {
    const token = localStorage.getItem('authToken');
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
}, error => {
    return Promise.reject(error);
});

// 响应拦截器
instance.interceptors.response.use(response => {
    if (response.status === 200) {
        return response.data;
    }
    return Promise.reject(response);
}, error => {
    return Promise.reject(error);
});

/**
 * get参数转换
 */
const queryChangeFun = result => {
    let queryString = Object.keys(result)
        .map(key => `${key}=${result[key]}`)
        .join('&');
    return queryString.length >= 2 ? '?' + queryString : '';
};

// 封装通用请求方法
const askApi = (method = 'get', url = "", params = {}, query = {}, headers = {}) => {
    const config = {
        method: method.toLowerCase(), // 统一转换为小写
        url,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            ...headers // 合并自定义headers
        }
    };

    // 根据请求方法处理参数
    if (method.toLowerCase() === 'get') {
        // config.params = query; // get请求使用params
        config.url = url + queryChangeFun(query);
    } else {
        config.data = params; // 其他请求使用data
    }
    return instance(config)
};

export default askApi;